//
//  ClubPasswordLoginView.swift
//  77Club
//
//  Created by Apple on 2024/8/29.
//

import UIKit

class ClubPasswordLoginView: UIView {

    let phoneTextfield = c_make_ex(UITextField.self)
        .bgColor(.white).corner(25).color(.black).font(14.font_medium)
        .placeholder("请输入手机号码").end()
    let passwordTextfield = c_make_ex(UITextField.self)
        .bgColor(.white).corner(25).color(.black).font(14.font_medium)
        .placeholder("请输入6~12位密码").end()
    private let forgetButton = c_make_ex(UIButton.self)
        .text("忘记密码？").color("#FF8319").font(13.font_medium).end()
    private let showButton = c_make_ex(UIButton.self)
        .image("Login_hidden").image("Login_show", state: .selected).end()
    private var rememberButton = UIIconButton(style: .leading(itemSpace: 3))
    
    var forgetBlock: (() -> Void)?
    var updateStateBlock: ((_ enable: Bool) -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        subviews{
            phoneTextfield
            passwordTextfield
            forgetButton
            rememberButton
            showButton
        }
        
        phoneTextfield.leading(16).trailing(16).height(50).top(0)
        passwordTextfield.leading(16).trailing(16).height(50)
        passwordTextfield.Top == phoneTextfield.Bottom + 24
        rememberButton.leading(16).height(14).bottom(0)
        rememberButton.Top == passwordTextfield.Bottom + 12
        forgetButton.trailing(16).height(14)
        forgetButton.CenterY == rememberButton.CenterY
        showButton.size(24)
        showButton.CenterY == passwordTextfield.CenterY
        showButton.Trailing == passwordTextfield.Trailing - 16
        
        phoneTextfield.style { v in
            v.placehold("#7B7D80".toColor, font: 14.font_medium)
            let leftImageV = UIImageView(frame: CGRect(x: 13, y: 13, width: 24, height: 24))
            leftImageV.image = "Login_phone".toImage
            let leftView = UIView(frame: CGRect(x: 0, y: 0, width: 56, height: 50))
            leftView.addSubview(leftImageV)
            v.leftView = leftView
            v.leftViewMode = .always
            v.delegate = self
            v.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
        }
        passwordTextfield.style { v in
            v.placehold("#7B7D80".toColor, font: 14.font_medium)
            let leftImageV = UIImageView(frame: CGRect(x: 13, y: 13, width: 24, height: 24))
            leftImageV.image = "Login_password".toImage
            let leftView = UIView(frame: CGRect(x: 0, y: 0, width: 56, height: 50))
            leftView.addSubview(leftImageV)
            v.leftView = leftView
            v.leftViewMode = .always
            v.isSecureTextEntry = true
            v.delegate = self
            v.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
        }
        rememberButton.style { v in
            v.iconSize = CGSize(width: 14, height: 14)
            v.setImage("Login_checkNor".toImage, for: .normal)
            v.setImage("Login_checkSel".toImage, for: .selected)
            v.setTitle("记住密码", for: .normal)
            v.setTitleColor("#323233".toColor, for: .normal)
            v.titleLabel?.font = 14.font_medium
            v.addTarget(self, action: #selector(clickRememberButton), for: .touchUpInside)
            v.isSelected = UserDefaultsManager.getBool(forKey: .isRemember)
        }
        forgetButton.contentHorizontalAlignment = .right
        rememberButton.contentHorizontalAlignment = .left
        
        forgetButton.addTarget(self, action: #selector(clickForgetButton), for: .touchUpInside)
        showButton.addTarget(self, action: #selector(clickShowButton), for: .touchUpInside)
        
        if UserDefaultsManager.getBool(forKey: .isRemember) {
             
            if let phoneNum = UserDefaultsManager.getString(forKey: .phone), phoneNum.count > 0 {
                phoneTextfield.text = phoneNum
            }
            
            if let password = UserDefaultsManager.getString(forKey: .password), password.count > 0 {
                passwordTextfield.text = password
            }
            
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
                self.updateLoginButtonState()
            }
            
        }
    }
    
    func clearInfo(){
        
        phoneTextfield.text = ""
        passwordTextfield.text = ""
        if UserDefaultsManager.getBool(forKey: .isRemember) {
             
            if let phoneNum = UserDefaultsManager.getString(forKey: .phone), phoneNum.count > 0 {
                phoneTextfield.text = phoneNum
            }
            
            if let password = UserDefaultsManager.getString(forKey: .password), password.count > 0 {
                passwordTextfield.text = password
            }
            
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
                self.updateLoginButtonState()
            }
            
        }        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

//MARK: action
extension ClubPasswordLoginView {
    
    @objc private func clickRememberButton(){
        
        rememberButton.isSelected = !rememberButton.isSelected
        UserDefaultsManager.setBool(rememberButton.isSelected, forKey: .isRemember)
    }
    
    @objc private func clickForgetButton(){
        forgetBlock?()
    }
    
    @objc private func clickShowButton(){
        
        showButton.isSelected = !showButton.isSelected
        passwordTextfield.isSecureTextEntry = !showButton.isSelected
    }
}

extension ClubPasswordLoginView: UITextFieldDelegate {
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        // 当前文本
        let currentText = textField.text ?? ""
        // 输入后的文本
        guard let stringRange = Range(range, in: currentText) else { return false }
        let updatedText = currentText.replacingCharacters(in: stringRange, with: string)
        var maxLength = 11
        if textField == passwordTextfield {
            maxLength = 12
        }
        
        // 检查输入后的文本是否超过最大长度
        return updatedText.count <= maxLength
    }
    
    func updateLoginButtonState(){
        
        if phoneTextfield.text?.count ?? 0 > 0 && passwordTextfield.text?.count ?? 0 > 0 {
            updateStateBlock?(true)
        }else{
            updateStateBlock?(false)
        }
    }
    
    @objc func textFieldDidChange(_ textField: UITextField) {
        print("Text changed: \(textField.text ?? "")")
        updateLoginButtonState()
    }
    
}
